import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ReplyForm } from '../entities/replyform.entity';
import { AskForm } from '../entities/askform.entity';

@Injectable()
export class ReplyFormService {
    constructor(
        @InjectRepository(ReplyForm)
        private replyFormRepository: Repository<ReplyForm>,
        @InjectRepository(AskForm)
        private askFormRepository: Repository<AskForm>,
    ) {}

    async findAll(): Promise<ReplyForm[]> {
        return this.replyFormRepository.find({
            relations: ['askForm']
        });
    }

    async findOne(id: number): Promise<ReplyForm> {
        const replyForm = await this.replyFormRepository.findOne({
            where: { id },
            relations: ['askForm']
        });
        if (!replyForm) {
            throw new NotFoundException(`ReplyForm with ID ${id} not found`);
        }
        return replyForm;
    }

    async create(replyForm: ReplyForm): Promise<ReplyForm> {
        // 保存回复表单
        const savedReplyForm = await this.replyFormRepository.save(replyForm);
        
        // 更新问题表单的isAnswered状态
        if (replyForm.askForm && replyForm.askForm.id) {
            await this.askFormRepository.update(replyForm.askForm.id, {
                isAnswered: true
            });
        }
        
        return this.findOne(savedReplyForm.id);
    }

    async update(id: number, replyForm: Partial<ReplyForm>): Promise<ReplyForm> {
        await this.findOne(id); // Check if it exists
        await this.replyFormRepository.update(id, replyForm);
        return this.findOne(id); // Return updated form
    }

    async remove(id: number): Promise<void> {
        // 先获取回复表单信息
        const replyForm = await this.findOne(id);
        if (!replyForm) {
            throw new NotFoundException(`ReplyForm with ID ${id} not found`);
        }

        // 删除回复表单
        const result = await this.replyFormRepository.delete(id);
        if (result.affected === 0) {
            throw new NotFoundException(`ReplyForm with ID ${id} not found`);
        }

        // 更新问题表单状态为未回复
        if (replyForm.askForm && replyForm.askForm.id) {
            await this.askFormRepository.update(replyForm.askForm.id, {
                isAnswered: false
            });
        }
    }
} 